<script setup lang="ts">
import HomeRequest from '@/request/homeRequest';
import { useAppStore } from '@/store';
import Location from '@/utils/location';
import useLoading from '@/hooks/useLoading';
import UserRequest from '@/request/userRequest';
import SelectAddressListPopup from '@/subcontract/home/submitOrder/component/receivingAddress/component/SelectAddressListPopup.vue';
import eventBus from '@/utils/eventBus';
import CascaderAddressListPopup from '@/subcontract/home/submitOrder/component/receivingAddress/component/CascaderAddressListPopup.vue';
import useToast from '@/hooks/useToast';

interface IProps {
  params: {
    beeperId: number;
    businessIds?: string;
    goodsIds?: string;
    serverIds?: string;
    thirdClassifyIds?: string;
    ruleIds?: string;
    variantIds: string;
  };
  callerDevicePartInfo: IObtainCallerDevicePartInfoRes;
  productList: IProductInformation[];
}

interface IState {
  show: boolean;
  address?: IListShippingAddressesRes;
  selectAddress?: IListShippingAddressesRes;
  addressList: IListShippingAddressesRes[];
  editHarvestAddressId?: number;
  isEditAddress: boolean; // 是否编辑过地址
}

type EmitEvents = {
  (event: 'change', payload: { address?: IListShippingAddressesRes; isEditAddress: boolean; off?: number }): void;
};

const props = defineProps<IProps>();
const store = useAppStore();
const { showLoading } = useLoading();
const { showToast } = useToast();
const state = reactive<IState>({ show: false, addressList: [], isEditAddress: false });
const emits = defineEmits<EmitEvents>();

onMounted(() => {
  // 如果不存在上门服务且 addressType === 1 （呼叫器地址和联系人） 时不显示
  if (!props.productList.some((item) => item.visitFlag) && props.callerDevicePartInfo.addressType === 1) return;
  fetchObtainHarvestAddress();
  fetchListShippingAddress();
  eventBus.on('callHarvestAddress', harvestCallHarvestAddress);
});

onUnmounted(() => {
  eventBus.off('callHarvestAddress');
});

watch(
  () => state.selectAddress,
  (selectAddress) => {
    emits('change', { address: selectAddress, isEditAddress: state.isEditAddress, off: state.address?.off });
  },
);

// 获得地址信息
const fetchObtainHarvestAddress = async () => {
  const { beeperId, variantIds } = props.params;
  let params: any = { beeperId, variantIds, hasLoading: true };
  // addressType === 3 符合条件的就近收货地址
  if (props.callerDevicePartInfo.addressType === 3) {
    if (store.beeperParams.latitude && store.beeperParams.longitude) {
      params = { ...params, latitude: store.beeperParams.latitude, longitude: store.beeperParams.longitude };
    } else {
      showLoading();
      const location = await Location.positioningLatitudeLongitude();
      if (!location) return;
      params = { ...params, latitude: location.latitude, longitude: location.longitude };
    }
  }
  HomeRequest.ObtainHarvestAddress(params).then((res) => {
    if (res.data.status === 1) {
      state.show = true;
      return;
    }
    if (res.data.status === 2) return;
    state.address = res.data;
    state.selectAddress = res.data;
    if ([2, 4, 6, 7, 8].some((item) => item === props.callerDevicePartInfo.addressType) && state.address.off === 2) {
      state.selectAddress.linkName = store.userInfo.nickName;
      state.selectAddress.phone = store.userInfo.phone;
    }
    if ([4, 6, 7, 8].some((item) => item === props.callerDevicePartInfo.addressType) && state.address.off === 2) {
      state.selectAddress.houseNumber = '';
      state.selectAddress.houseNumberId = 0;
    }
    if ([6, 7, 8].some((item) => item === props.callerDevicePartInfo.addressType) && state.address.off === 2) {
      state.selectAddress.floorName = '';
      state.selectAddress.floorId = 0;
    }
    if ([7, 8].some((item) => item === props.callerDevicePartInfo.addressType) && state.address.off === 2) {
      state.selectAddress.unitName = '';
      state.selectAddress.unitId = 0;
    }
    if (props.callerDevicePartInfo.addressType === 8) {
      state.selectAddress.buildName = '';
      state.selectAddress.buildId = 0;
    }
  });
};

// 处理事件总线通讯
const harvestCallHarvestAddress = (id?: number) => {
  state.editHarvestAddressId = id;
  state.isEditAddress = !!id;
  fetchListShippingAddress();
};

// 获得弹出层中的地址列表
const fetchListShippingAddress = () => {
  UserRequest.ListShippingAddress({ beeperId: store.$state.beeperId, variantIds: props.params.variantIds }).then((res) => {
    state.addressList = res.data;
    // 编辑地址后如果在配送范围内即用
    if (state.editHarvestAddressId) {
      const findItem = res.data.find((item) => item.harvestAddressId === state.editHarvestAddressId);
      if (findItem && findItem.state === 1) state.selectAddress = findItem;
    } else {
      state.selectAddress = state.address ? state.address : undefined;
    }
  });
};

// 处理地址列表选择
const handleAddressSelect = (item: IListShippingAddressesRes) => {
  state.selectAddress = item;
  state.isEditAddress = true;
  state.show = false;
};

// 处理地址楼栋选择器change事件
const handleCascaderAddressChange = (cascaderSelectedOptions: IBuildingTreeRes[]) => {
  const { addressType } = props.callerDevicePartInfo;
  const selectAddress: IListShippingAddressesRes = { ...state.selectAddress! };
  if (addressType === 4) {
    selectAddress!.houseNumber = cascaderSelectedOptions[0].name;
    selectAddress!.houseNumberId = Number(cascaderSelectedOptions[0].id);
  }
  if (addressType === 6 && cascaderSelectedOptions.length >= 2) {
    selectAddress!.floorName = cascaderSelectedOptions[0].name;
    selectAddress!.floorId = Number(cascaderSelectedOptions[0].id);
    selectAddress!.houseNumber = cascaderSelectedOptions[1].name;
    selectAddress!.houseNumberId = Number(cascaderSelectedOptions[1].id);
  }
  if (addressType === 7 && cascaderSelectedOptions.length >= 3) {
    selectAddress!.unitName = cascaderSelectedOptions[0].name;
    selectAddress!.unitId = Number(cascaderSelectedOptions[0].id);
    selectAddress!.floorName = cascaderSelectedOptions[1].name;
    selectAddress!.floorId = Number(cascaderSelectedOptions[1].id);
    selectAddress!.houseNumber = cascaderSelectedOptions[2].name;
    selectAddress!.houseNumberId = Number(cascaderSelectedOptions[2].id);
  }
  if (addressType === 8 && cascaderSelectedOptions.length >= 4) {
    selectAddress!.buildName = cascaderSelectedOptions[0].name;
    selectAddress!.buildId = Number(cascaderSelectedOptions[0].id);
    selectAddress!.unitName = cascaderSelectedOptions[1].name;
    selectAddress!.unitId = Number(cascaderSelectedOptions[1].id);
    selectAddress!.floorName = cascaderSelectedOptions[2].name;
    selectAddress!.floorId = Number(cascaderSelectedOptions[2].id);
    selectAddress!.houseNumber = cascaderSelectedOptions[3].name;
    selectAddress!.houseNumberId = Number(cascaderSelectedOptions[3].id);
  }
  if (selectAddress.houseNumber) {
    state.selectAddress = { ...state.selectAddress, ...selectAddress };
  }
};

// 选择地址点击
const handleSelectAddressClick = () => {
  if (props.callerDevicePartInfo.addressType === 3) {
    uni.authorize({
      scope: 'scope.userLocation',
      success: () => {
        state.show = true;
      },
      fail: () => {
        showToast('请授权地理位置权限');
      },
    });
  } else {
    state.show = true;
  }
};
</script>

<template>
  <view class="c-pd bg-white c-br" v-if="state.address || state.selectAddress">
    <view class="flex items-center" v-if="state.selectAddress" @click="state.show = true">
      <view class="flex-1 mr-12px">
        <text class="fw-bold">
          {{ state.selectAddress.address || '' }}
          {{ state.selectAddress.villageName || '' }}
          {{ state.selectAddress.buildName || '' }}
          {{ state.selectAddress.unitName || '' }}
          {{ state.selectAddress.floorName || '' }}
          {{ state.selectAddress.houseNumber || '' }}
        </text>
        <!--    需要填写额外信息，但是已经选择或新增了新地址   -->
        <view class="c-text-color-grey c-text-12 mt-12px" v-if="state.selectAddress && state.address && state.address.off === 2 && state.address.harvestAddressId !== state.selectAddress.harvestAddressId">
          <text class="mr-8px">{{ state.selectAddress.linkName }}</text>
          <text>{{ state.selectAddress.phone }}</text>
        </view>
        <!--    对无地址数据的处理    -->
        <view class="c-text-color-grey c-text-12 mt-12px" v-if="!state.address && state.selectAddress">
          <text class="mr-8px">{{ state.selectAddress.linkName }}</text>
          <text>{{ state.selectAddress.phone }}</text>
        </view>
        <!--    对不需要显示额外补充信息处理    -->
        <view class="c-text-color-grey c-text-12 mt-12px" v-if="state.address && state.selectAddress && state.address.off !== 2">
          <text class="mr-8px">{{ state.selectAddress.linkName }}</text>
          <text>{{ state.selectAddress.phone }}</text>
        </view>
      </view>
      <i class="i-mingcute:right-fill text-22px" />
    </view>
    <template v-if="state.address && state.selectAddress && state.address.off === 2 && state.selectAddress.harvestAddressId === state.address.harvestAddressId">
      <van-divider />
      <CascaderAddressListPopup :callerDevicePartInfo="props.callerDevicePartInfo" @change="handleCascaderAddressChange" />
      <van-field clearable clickable :value="state.selectAddress.linkName" label="联系人" placeholder="请输入联系人" required @change="state.selectAddress.linkName = $event.detail" />
      <van-field clearable clickable :value="state.selectAddress.phone" label="电话" placeholder="请输入联系人电话" required @change="state.selectAddress.phone = $event.detail" />
    </template>
  </view>
  <view class="c-pd bg-white c-br flex items-center" v-else @click="handleSelectAddressClick">
    <i class="i-akar-icons:info-fill c-color" />
    <text class="ml-8px c-color">选择地址</text>
  </view>

  <SelectAddressListPopup :show="state.show" :variantIds="props.params.variantIds" :select-address="state.selectAddress" :address-list="state.addressList" @change="({ show }) => (state.show = show)" @select="({ data }) => handleAddressSelect(data)" />
</template>
